#include "UsrAI.h"
#include<set>
#include <iostream>
#include<unordered_map>
using namespace std;
tagGame tagUsrGame;
ins UsrIns;
tagInfo info;
const int HOME_MAX=2;
char Mymap[128][128]={0};
int begin_x=0,begin_y=0;
int start_x=0,start_y=0;
int center_x=0,center_y=0;
bool home_flag=false;

//村民分类列表
vector<tagFarmer>idleFarmer;               // 存储闲置的农民
vector<tagFarmer>fishingFarmer;            // 存储捕鱼的农民
vector<tagFarmer>cuttingFarmer;            // 存储砍树的农民
vector<tagFarmer>buildingHouseFarmer;      // 存储建造房子的农民
//映射表
map<int,int>SN_to_Sort;
map<int,tagResource>SN_to_Resource;
map<int,tagBuilding>SN_to_Building;

void UsrAI::processData()
{
    info=getInfo();
    //遍历并统计农民情况
    farmerManage();
    //安排1个农民建房
    if(idleFarmer.size()) {
        House_build(idleFarmer[idleFarmer.size()-1]);
    }
     produce_farmer();
     // 安排 1 个农民捕鱼
     if(idleFarmer.size()) {
          HumanAction(idleFarmer[idleFarmer.size()-1].SN, findResource(idleFarmer[idleFarmer.size()-1], RESOURCE_FISH));
          DebugText("安排农民"+QString::number(idleFarmer[idleFarmer.size()-1].SN)+"捕鱼");
          fishingFarmer.push_back(idleFarmer[idleFarmer.size()-1]);              // 加入捕鱼农民数组
          idleFarmer.pop_back();
     }
     // 安排不超过 1+1 个农民砍树
     while(idleFarmer.size() && cuttingFarmer.size()<2) {
         HumanAction(idleFarmer[idleFarmer.size()-1].SN, findResource(idleFarmer[idleFarmer.size()-1], RESOURCE_TREE));
         DebugText("安排农民" + QString::number(idleFarmer[idleFarmer.size()-1].SN) + "砍树");
         cuttingFarmer.push_back(idleFarmer[idleFarmer.size()-1]);            // 加入砍树农民数组
         idleFarmer.pop_back();
     }
     // 安排 1 个农民建造船坞
     if(!idleFarmer.empty()) {
      int x=-1,y=-1;
      //计算距离村民最近的海洋的块坐标
      double dis = 1e6;
      for(size_t i = 0; i <info.resources.size() ; i++) {
          const tagResource& res=info.resources[i];
          if(res.Type!=RESOURCE_FISH||res.Cnt<=0)
              continue;
          double tempDistance = calDistance(idleFarmer[idleFarmer.size()-1].DR, idleFarmer[idleFarmer.size()-1].UR, res.DR, res.UR);
          if(dis > tempDistance) {
              dis = tempDistance;
              start_x=res.BlockDR;
              start_y=res.BlockUR;
          }
      }
        for(int i = start_x + 1; i < 128; i++) {
            for (int j = start_y + 1; j < 128; j++) {
                if (i + 1 < 128 && j + 1 < 128) {
                    // 检查四个位置是否都是海洋
                    if ((*info.theMap)[i][j].type == MAPPATTERN_OCEAN &&
                        (*info.theMap)[i + 1][j].type == MAPPATTERN_OCEAN &&
                        (*info.theMap)[i][j + 1].type == MAPPATTERN_OCEAN &&
                        (*info.theMap)[i + 1][j + 1].type == MAPPATTERN_OCEAN) {
                        // 检查高度是否相等
                            int height = (*info.theMap)[i][j].height;
                            if ((*info.theMap)[i + 1][j].height == height &&
                             (*info.theMap)[i][j + 1].height == height &&
                             (*info.theMap)[i + 1][j + 1].height == height) {
                                    // 找到符合条件的2*2空地，返回左下角坐标
                                     x = i;
                                     y = j;
                                     break;
                            }
                    }
                 }
            }
            if(x!=-1)
                break;
        }
        HumanBuild(idleFarmer[idleFarmer.size()-1].SN,BUILDING_DOCK,x,y);
        DebugText("安排农民"+QString::number(idleFarmer[idleFarmer.size()-1].SN)+"建船坞");
        buildingHouseFarmer.push_back(idleFarmer[idleFarmer.size()-1]);              // 加入建房农民数组
        idleFarmer.pop_back();
     }
    //船坞生产渔船
     for (tagBuilding& building : info.buildings) {
             //如果船坞空闲且木头数量足够则生产渔船
             if (building.Type == BUILDING_DOCK && building.Project == 0 && info.Wood >= BUILDING_DOCK_CREATE_SAILING_WOOD ) {
                 BuildingAction(building.SN, BUILDING_DOCK_CREATE_SAILING);
                 break;
             }
         }

    return ;
}
//从市镇中心开始查找2*2的空地
int UsrAI::find_block(int &x,int &y){
    if(info.theMap ==nullptr){
        cout<<"info.theMap is null!"<<endl;
        return 0;
    }
    for(int i = begin_x + 1; i < 128; i++) {
        for (int j = begin_y + 1; j < 128; j++) {
            if (i + 1 < 128 && j + 1 < 128) {
                // 检查四个位置是否都是陆地
                if ((*info.theMap)[i][j].type == MAPPATTERN_GRASS &&
                    (*info.theMap)[i + 1][j].type == MAPPATTERN_GRASS &&
                    (*info.theMap)[i][j + 1].type == MAPPATTERN_GRASS &&
                    (*info.theMap)[i + 1][j + 1].type == MAPPATTERN_GRASS) {
                    cout << "找到陆地: " << i << ", " << j << endl;
                // 检查高度是否相等（平地）
                    int height = (*info.theMap)[i][j].height;
                    if ((*info.theMap)[i + 1][j].height == height &&
                     (*info.theMap)[i][j + 1].height == height &&
                     (*info.theMap)[i + 1][j + 1].height == height) {
                            // 找到符合条件的2*2空地，返回左下角坐标
                             x = i;
                             y = j;
                             cout << "找到空地: " << x << ", " << y << endl;
                             return 1; // 返回1表示成功找到
                    }
                 }
              }
           }
       }
    return 0; // 返回0表示未找到合适的空地
}
//一个空闲村民建造两座房屋
void UsrAI::House_build(tagFarmer farmer){
    //初始化市镇中心坐标
        if(center_x==0 && center_y==0){
            for(tagBuilding &building:info.buildings){
                if(building.Type==BUILDING_CENTER){
                    center_x=building.BlockDR;
                    center_y=building.BlockUR;
                }
            }
        }
    //初始化搜索的起始坐标
        if(begin_x==0 && begin_y==0){
            begin_x=center_x;
            begin_y=center_y;
        }
    //统计当前已建成的房屋数量
        int home_count=0;
        for(tagBuilding &building:info.buildings){
            if(building.Type==BUILDING_HOME){
                home_count++;
            }
        }
    //如果已建数量未达标，继续找空地建造房屋
        if(home_count<HOME_MAX){
            int new_home_x,new_home_y;//新房屋的坐标
     //寻找新的空地（从上次搜索的位置开始，避免重复）
            if(find_block(new_home_x,new_home_y)){
                HumanBuild(farmer.SN,BUILDING_HOME,new_home_x,new_home_y);
                begin_x=new_home_x;
                begin_y=new_home_y;
            }
            DebugText("安排农民"+QString::number(farmer.SN)+"建房子");
            buildingHouseFarmer.push_back(farmer);              // 加入建房农民数组
            idleFarmer.pop_back();
        }

}
// 遍历并统计农民情况
void UsrAI::farmerManage (){
    for(tagFarmer myFarmer:info.farmers) {
        if(myFarmer.FarmerSort == 0){
// 将闲置农民加入数组
          if(myFarmer.NowState == HUMAN_STATE_IDLE )    idleFarmer.push_back(myFarmer);
          if(myFarmer.NowState == HUMAN_STATE_WORKING){
            int Type = SN_to_Sort[myFarmer.WorkObjectSN];
            // 状态对应
            if(Type == RESOURCE_TREE) cuttingFarmer.push_back(myFarmer);
            if(Type == RESOURCE_FISH) fishingFarmer.push_back(myFarmer);
            if(Type == BUILDING_HOME) buildingHouseFarmer.push_back(myFarmer);
          }
        }
    }
}
void UsrAI::cutTree(){
    ;
}
void UsrAI::Dock_build(){

}
void UsrAI::produce_farmer(){
    for(tagBuilding&building:info.buildings){
        //如果市镇中心空闲，且有足够食物，且农民数量小于人口上限，则生产农民
        if(building.Type==BUILDING_CENTER&&building.Project==0&&info.Meat>=BUILDING_CENTER_CREATEFARMER_FOOD
                &&info.farmers.size()<info.Human_MaxNum){
            BuildingAction(building.SN,BUILDING_CENTER_CREATEFARMER);
            break;
        }
    }

}

void UsrAI::initMap(){
    for(int i=0;i<128;i++){
        for(int j=0;j<128;j++){
            if ((*info.theMap)[i][j].type == MAPPATTERN_GRASS){
                Mymap[i][j]='0';
            }
            else if((*info.theMap)[i][j].type ==MAPPATTERN_OCEAN){
                Mymap[i][j]='-';
            }
        }
    }
    mark_Resources();
    mark_Buildings();
    mark_Units();
    for(int i=0;i<128;i++){
        for(int j=0;j<128;j++){
            cout<<Mymap[i][j];
        }
        cout<<endl;
    }
}
void UsrAI::mark_Resources(){
    for(tagResource&resources:info.resources){
        if(resources.Type){
            int i=int (resources.BlockDR);
            int j=int (resources.BlockUR);
            Mymap[i][j]='A';
        }

    }
}
void UsrAI::mark_Buildings(){
    for(tagBuilding &building:info.buildings){
        if(building.Type){
            int i=building.BlockDR;
            int j=building.BlockUR;
            Mymap[i][j]='a';
        }

    }
}
void UsrAI::mark_Units(){
    for(tagFarmer&farmer:info.farmers){
        if(farmer.Blood){
            int i=farmer.BlockDR;
            int j=farmer.BlockUR;
            Mymap[i][j]='*';
        }
    };
}
int UsrAI::findResource(tagFarmer farmer,int type){
    int targetResSN = 0;
    if(farmer. NowState == HUMAN_STATE_IDLE ) {
                // 计算出距离该村民最近的资源的全局编号SN
                double dis = 1e6;
                for(size_t i = 0; i <info.resources.size() ; i++) {
                    const tagResource& res=info.resources[i];
                    if(res.Type!=type||res.Cnt<=0)
                        continue;
                    double tempDistance = calDistance(farmer.DR, farmer.UR, res.DR, res.UR);
                    if(dis > tempDistance) {
                        dis = tempDistance;
                        targetResSN = info.resources[i].SN;
                        }
                }
        }
    return targetResSN;
}
